package org.jeecg.modules.lab.utensil.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.lab.cert.client.UserClient;
import org.jeecg.modules.lab.chemical.entity.LabChemical;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.user.entity.SysUser;
import org.jeecg.modules.lab.utensil.entity.LabUtensil;
import org.jeecg.modules.lab.utensil.entity.LabUtensilCheck;
import org.jeecg.modules.lab.utensil.entity.LabUtensilChecklist;
import org.jeecg.modules.lab.utensil.service.ILabUtensilCheckService;
import org.jeecg.modules.lab.utensil.service.ILabUtensilChecklistService;
import org.jeecg.modules.lab.utensil.service.ILabUtensilService;
import org.jeecg.modules.lab.utensil.vo.LabUtensilCheckPage;
import org.jeecg.modules.lab.utensil.vo.LabUtensilCheckVo;
import org.jeecg.modules.lab.utensil.vo.LabUtensilChecklistVo;
import org.jeecg.modules.lab.utensil.vo.LabUtensilVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * @Description: 器具检测申请表
 * @Author: jeecg-boot
 * @Date: 2023-08-22
 * @Version: V1.0
 */
@Api(tags = "器具检测申请表")
@RestController
@RequestMapping("/utensil/labUtensilCheck")
@Slf4j
public class LabUtensilCheckController {
    @Autowired
    private ILabUtensilCheckService labUtensilCheckService;
    @Autowired
    private ILabUtensilChecklistService labUtensilChecklistService;
    @Autowired
    private ILabUtensilService labUtensilService;
    @Autowired
    private ILabCronJobService labCronJobService;
    @Autowired
    private UserClient userClient;

    /**
     * 分页列表查询
     *
     * @param labUtensilCheck
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "器具检测申请表-分页列表查询")
    @ApiOperation(value = "器具检测申请表-分页列表查询", notes = "器具检测申请表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabUtensilCheck>> queryPageList(LabUtensilCheck labUtensilCheck,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<LabUtensilCheck> queryWrapper = QueryGenerator.initQueryWrapper(labUtensilCheck, req.getParameterMap());
        Page<LabUtensilCheck> page = new Page<LabUtensilCheck>(pageNo, pageSize);
        IPage<LabUtensilCheck> pageList = labUtensilCheckService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping(value = "queryAllCheck")
    public Result<List<LabUtensilChecklistVo>> queryCheck(@RequestParam(name = "ids", defaultValue = "") String ids) {

        QueryWrapper<LabUtensil> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","待检定");
        if( ids !=null &&  !"".equals(ids)){
            List<String> idList = new ArrayList<>();
            String[] uIds = ids.split(",");
            for (int i = 0; i < uIds.length; i++) {
                idList.add(uIds[i]);
            }
            queryWrapper.in("id",idList);
        }
        List<LabUtensil> labUtensils = labUtensilService.list(queryWrapper);
        List<LabUtensilChecklistVo> checks = new ArrayList<>();
        labUtensils.forEach(e -> {
            SysUser user = userClient.queryById(e.getPersonResponsible()).getResult();
            LabUtensilChecklistVo checklist = new LabUtensilChecklistVo();
            checklist.setUteName(e.getUteName());
            checklist.setUteType(e.getSpecification());
            checklist.setUteRef(e.getManuNumber());
            checklist.setDri(e.getPersonResponsible());
            checklist.setLastType(e.getTraceabilityMethod());
            checklist.setLocale(e.getFieldInspect());
            checklist.setUteId(e.getId());
            if (user!=null) {
                checklist.setDriName(user.getRealname());
            }
            checks.add(checklist);
        });
        return Result.ok(checks);
    }



    /**
     * 添加
     *
     * @param labUtensilCheckVo
     * @return
     */
    @AutoLog(value = "器具检测申请表-添加")
    @ApiOperation(value = "器具检测申请表-添加", notes = "器具检测申请表-添加")
//   @RequiresPermissions("utensilCheck:lab_utensil_check:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabUtensilCheckVo labUtensilCheckVo) {
        LabUtensilCheck labUtensilCheck = new LabUtensilCheck();
        BeanUtils.copyProperties(labUtensilCheckVo, labUtensilCheck);
        labUtensilCheckService.save(labUtensilCheck);
        List<LabUtensilChecklist> checkList = labUtensilCheckVo.getCheckList();

        List<LabUtensil> labUtensils =  new ArrayList<>();
        checkList.forEach(e -> {
            e.setCheckId(labUtensilCheck.getId());
            e.setListState("检定中");

            //更新器具信息
            LabUtensil labUtensil = new  LabUtensil();
            labUtensil.setId(e.getUteId());
            labUtensil.setStatus("检定中");
            labUtensil.setSynFlag("1");
            labUtensils.add(labUtensil);

        });
        labUtensilChecklistService.saveBatch(checkList);
        labUtensilService.updateBatchById(labUtensils);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_utensil_check", "0", time, 1));
            jobs.add(new LabCronJob("lab_utensil_checklist", "0", time, 2));
            jobs.add(new LabCronJob("lab_utensil", "1", time, 3));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("检定单添加成功！");

    }

    //根据申请单id查询清单表信息
    @GetMapping(value = "/checkId")
    public Result<List<LabUtensilChecklist>> checkId(@RequestParam(name = "id", defaultValue = "") String id) {
        List<LabUtensilChecklist> list = labUtensilChecklistService.list(new LambdaQueryWrapper<LabUtensilChecklist>().eq(LabUtensilChecklist::getCheckId, id));
        return Result.ok(list);
    }

    //送检
    @GetMapping(value = "updateCheck")
    public Result updateCheck(@RequestParam(name = "id", defaultValue = "") String id) {
        LabUtensilCheck check = labUtensilCheckService.getById(id);
        check.setCheckState("已送检");
        check.setSynFlag("1");
        //送检单中的所有器具
        List<LabUtensilChecklist> list = labUtensilChecklistService.list(new LambdaQueryWrapper<LabUtensilChecklist>().eq(LabUtensilChecklist::getCheckId, id));
        List<LabUtensil> labUtensils = new ArrayList<>();
        list.forEach(e -> {
            e.setListState("检定中");
            e.setSynFlag("1");
            LabUtensil utensil = labUtensilService.getOne(new LambdaQueryWrapper<LabUtensil>().eq(LabUtensil::getId, e.getUteId()));
            utensil.setStatus("检定中");
            utensil.setSynFlag("1");
            labUtensils.add(utensil);
        });
        try {
            labUtensilCheckService.updateById(check);
            labUtensilChecklistService.updateBatchById(list);
            labUtensilService.updateBatchById(labUtensils);

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add(new LabCronJob("lab_utensil_check", "1", time, 1));
                jobs.add(new LabCronJob("lab_utensil_checklist", "1", time, 2));
                jobs.add(new LabCronJob("lab_utensil", "1", time, 3));
                labCronJobService.saveBatch(jobs);
            }
            return Result.ok("已送检");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 编辑
     *
     * @param labUtensilCheckVo
     * @return
     */
    @AutoLog(value = "器具检测申请表-编辑")
    @ApiOperation(value = "器具检测申请表-编辑", notes = "器具检测申请表-编辑")
//   @RequiresPermissions("utensilCheck:lab_utensil_check:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabUtensilCheckVo labUtensilCheckVo) {
        LabUtensilCheck labUtensilCheck = new LabUtensilCheck();
        BeanUtils.copyProperties(labUtensilCheckVo, labUtensilCheck);
        labUtensilCheck.setSynFlag("1");
        labUtensilCheckVo.getCheckList().forEach(e -> {
            e.setCheckId(labUtensilCheck.getId());
            e.setSynFlag("0");
            e.setId("");
        });
        try {
            labUtensilCheckService.updateById(labUtensilCheck);
            labUtensilChecklistService.remove(new LambdaQueryWrapper<LabUtensilChecklist>().eq(LabUtensilChecklist::getCheckId, labUtensilCheck.getId()));
            labUtensilChecklistService.saveBatch(labUtensilCheckVo.getCheckList());
//            labUtensilCheckService.updateMain(labUtensilCheck, labUtensilCheckPage.getLabUtensilChecklistList());

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                String condition = "check_id='" + labUtensilCheck.getId() + "'";
                jobs.add(new LabCronJob("lab_utensil_check", "1", time, 1));
                jobs.add(new LabCronJob("lab_utensil_checklist", "2", condition, time, 2));
                jobs.add(new LabCronJob("lab_utensil_checklist", "0", time, 3));
                labCronJobService.saveBatch(jobs);
            }
            return Result.OK("编辑成功!");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "器具检测申请表-通过id删除")
    @ApiOperation(value = "器具检测申请表-通过id删除", notes = "器具检测申请表-通过id删除")
//   @RequiresPermissions("utensilCheck:lab_utensil_check:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            labUtensilCheckService.delete(id);

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                String condition1 = "id='" + id + "'";
                String condition2 = "check_id='" + id + "'";
                jobs.add(new LabCronJob("lab_utensil_check", "2", condition1, time, 1));
                jobs.add(new LabCronJob("lab_utensil_checklist", "2", condition2, time, 2));
                labCronJobService.saveBatch(jobs);
            }
            return Result.OK("删除成功!");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "器具检测申请表-批量删除")
    @ApiOperation(value = "器具检测申请表-批量删除", notes = "器具检测申请表-批量删除")
//   @RequiresPermissions("utensilCheck:lab_utensil_check:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labUtensilCheckService.delBatchMain(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            String[] idList = ids.split(",");
            for (int i = 0; i < idList.length; i++) {
                String condition1 = "id='" + idList[i] + "'";
                String condition2 = "check_id='" + idList[i] + "'";
                jobs.add(new LabCronJob("lab_utensil_check", "2", condition1, time));
                jobs.add(new LabCronJob("lab_utensil_checklist", "2", condition2, time));
            }
            for (int i = 0; i < jobs.size(); i++) {
                jobs.get(i).setOrderNum(i + 1);
            }
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "器具检测申请表-通过id查询")
    @ApiOperation(value = "器具检测申请表-通过id查询", notes = "器具检测申请表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabUtensilCheck> queryById(@RequestParam(name = "id", required = true) String id) {
        LabUtensilCheck labUtensilCheck = labUtensilCheckService.getById(id);
        if (labUtensilCheck == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labUtensilCheck);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "器具检测详情清单通过主表ID查询")
    @ApiOperation(value = "器具检测详情清单主表ID查询", notes = "器具检测详情清单-通主表ID查询")
    @GetMapping(value = "/queryLabUtensilChecklistByMainId")
    public Result<List<LabUtensilChecklist>> queryLabUtensilChecklistListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<LabUtensilChecklist> labUtensilChecklistList = labUtensilChecklistService.selectByMainId(id);
        return Result.OK(labUtensilChecklistList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labUtensilCheck
     */
//   @RequiresPermissions("utensilCheck:lab_utensil_check:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabUtensilCheck labUtensilCheck) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<LabUtensilCheck> queryWrapper = QueryGenerator.initQueryWrapper(labUtensilCheck, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<LabUtensilCheck> labUtensilCheckList = labUtensilCheckService.list(queryWrapper);

        // Step.3 组装pageList
        List<LabUtensilCheckPage> pageList = new ArrayList<LabUtensilCheckPage>();
        for (LabUtensilCheck main : labUtensilCheckList) {
            LabUtensilCheckPage vo = new LabUtensilCheckPage();
            BeanUtils.copyProperties(main, vo);
            List<LabUtensilChecklist> labUtensilChecklistList = labUtensilChecklistService.selectByMainId(main.getId());
            vo.setLabUtensilChecklistList(labUtensilChecklistList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "器具检测申请表列表");
        mv.addObject(NormalExcelConstants.CLASS, LabUtensilCheckPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("器具检测申请表数据", "导出人:" + sysUser.getRealname(), "器具检测申请表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//   @RequiresPermissions("utensilCheck:lab_utensil_check:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<LabUtensilCheckPage> list = ExcelImportUtil.importExcel(file.getInputStream(), LabUtensilCheckPage.class, params);
                for (LabUtensilCheckPage page : list) {
                    LabUtensilCheck po = new LabUtensilCheck();
                    BeanUtils.copyProperties(page, po);
                    labUtensilCheckService.saveMain(page);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
